<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>

      <el-button type="primary" @click="getCater">添加分类</el-button>
      <!-- selection-type是否显示复选框 border边框 stripe条纹 data数据 columns 如何渲染列 expand-type 是否显示扩展 show-index是否显示序号 index-text 序号列名字 -->
      <tree-table show-index index-text="序号" :expand-type="false" :selection-type="false" :data="data" :columns="columns"
        border stripe>

        <template slot="istrue" slot-scope="scope">
          <i v-if="!scope.row.cat_deleted" class="el-icon-success"></i>
          <i v-else class="el-icon-error"></i>
        </template>

        <template slot="sort" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag v-if="scope.row.cat_level === 1" size="mini" type="success">二级</el-tag>
          <el-tag v-if="scope.row.cat_level === 2" size="mini" type="warning">三级</el-tag>
        </template>

        <!-- 具名插槽 -->
        <template slot="like" slot-scope="scope">
          <!-- 修改 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="getCateRow(scope.row)"></el-button>
          <!-- 删除 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCate(scope.row.cat_id)"></el-button>
        </template>
      </tree-table>
      <!-- page-sizes条数的下拉框,,当前显示的是第几条 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagenum"
        :page-sizes="[5, 10, 15, 20]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <el-dialog title="添加分类" :visible.sync="dialogVisible" width="50%">
      <el-form ref="addform" :model="addform" :rules="addformRule" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addform.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader style="width: 100%;" v-model="addform.cat_pid" :options="options" :props="props"
            clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategories">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改分类" :visible.sync="dialogVisibleUpdate" width="50%">
      <el-form ref="updateform" :model="addform" :rules="addformRule" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addform.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUpdate = false">取 消</el-button>
        <el-button type="primary" @click="updateCategories">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TreeTable from "vue-table-with-tree-grid"
import request from '@/utils/request';
export default {
  components: {
    TreeTable
  },
  data () {
    return {
      pagenum: 1,
      pagesize: 5,
      total: 0,
      data: [],
      // 列,名字和对象里边的属性的值
      columns: [
        {
          label: '分类名字',
          prop: 'cat_name',
          width: '400px'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          minWidth: '50px',
          type: 'template',
          // 插槽的名字
          template: 'istrue'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          // 插槽的名字
          template: 'sort'
        },
        {
          label: '操作',
          minWidth: '200px',
          type: 'template',
          // 插槽的名字
          template: 'like'
        }
      ],
      // 控制添加分类的显示
      dialogVisible: false,
      // 添加的表单信息
      addform: {
        cat_pid: [],
        cat_name: "",
        cat_level: 0
      },
      // 校验规则
      addformRule: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 级联数据
      options: [],
      // 级联的设置
      props: {
        label: 'cat_name',
        value: 'cat_id',
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // 修改分类
      dialogVisibleUpdate: false
    }
  },
  // 页面渲染成功的时候执行
  mounted () {
    this.getCategoriesList()
  },
  methods: {
    handleSizeChange (size) {
      // 页面的条数
      this.pagesize = size
      // 重新获取数据
      this.getCategoriesList()
      // console.log("handleSizeChange", size);
    },
    handleCurrentChange (num) {
      // 改变当前页数
      this.pagenum = num
      // 重新获取数据
      this.getCategoriesList()
      // console.log("handleCurrentChange", num);
    },
    // 分页获取列表数据
    async getCategoriesList () {
      const { data: { data, meta } } = await request({
        url: '/categories',
        method: "GET",
        params: {
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status !== 200) {
        return this.$message.error("获取分类失败")
      }
      this.data = data.result
      this.total = data.total
    },
    // 根据类型获取级联数据
    async getCater () {
      this.dialogVisible = true
      const { data: { data, meta } } = await request({
        url: "/categories",
        method: "GET",
        params: {
          type: 2
        }
      })
      if (meta.status !== 200) {
        return this.$message.error("获取父级分类失败")
      }
      this.options = data
      // console.log(data);
    },
    async addCategories () {
      this.$refs.addform.validate(async (valid) => {
        // 没有通过校验
        if (!valid) {
          return this.$message.error("请填写正确数据")
        }
        const length = this.addform.cat_pid.length
        // 0 1级 1 2级 2三级
        this.addform.cat_level = length
        if (length !== 0) {
          this.addform.cat_pid = this.addform.cat_pid[length - 1]
        } else {
          this.addform.cat_pid = 0
        }
        // console.log(this.addform);
        const { data: { meta } } = await request({
          url: "/categories",
          method: "POST",
          data: this.addform
        })
        if (meta.status !== 201) {
          return this.$message.error('添加分类失败')
        }
        this.$message.success('添加成功')
        this.dialogVisible = false
        // 将表单的数据重置
        this.addform = this.$options.data().addform
        this.getCategoriesList()
      })
    },
    // 根据id删除分类
    async delCate (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: { meta } } = await request({
          url: `categories/${id}`,
          method: "delete"
        })
        if (meta.status !== 200) {
          return this.$message.error("删除失败")
        }
        this.$message.success("删除成功")
        // 重新渲染页面
        this.getCategoriesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取分类数据
    getCateRow (row) {
      // 给表单赋值
      this.addform = row
      // 显示对话框
      this.dialogVisibleUpdate = true
    },
    // 提交更新数据
    async updateCategories () {
      const { data: { meta } } = await request({
        url: `categories/${this.addform.cat_id}`,
        method: "PUT",
        data: this.addform
      })
      if (meta.status !== 200) {
        return this.$message.error("更新失败")
      }
      this.dialogVisibleUpdate = false
      this.$message.success("更新成功")
      // 刷新页面
      this.getCategoriesList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-icon-success {
  color: greenyellow;
}

.el-icon-error {
  color: red
}
</style>
